package com.paipai.ws;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WsHandler extends TextWebSocketHandler {
    private Map<String, WebSocketSession> onlines = new ConcurrentHashMap<String, WebSocketSession>();

    //建立连接,把session存入map中
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("建立连接" + session.getId());
        onlines.put(session.getId(), session);
    }

    //断开连接，把session移除
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("断开连接" + session.getId());
        onlines.remove(session.getId());
    }

    //处理接收到的消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        String roundId = session.getAttributes().get("roundId").toString();
        for (Map.Entry<String, WebSocketSession> et : onlines.entrySet()) {
            //判断传入场次id与map中存放id匹配，转发
            if (et.getValue().getAttributes().get("roundId").toString().equals(roundId)) {
                et.getValue().sendMessage(message);
            }
        }
    }
}
